package com.ruoyi.spider.util;

import org.springframework.web.util.UriUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import static org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.DEFAULT_CHARSET;

public class ImgStrUtils {
    public static String convertImg(ArrayList<String> urlList){

        StringBuffer imgString = new StringBuffer();

        for (String url : urlList) {
            StringBuffer stringBuffer = new StringBuffer("</br><p><img alt=\"\" src=\"");
            stringBuffer.append(url);
            stringBuffer.append("\" style=\"width: 645px;\"></p> \n" + " ");
            imgString.append(stringBuffer.toString());
        }

        return imgString.toString();
    }


    /**
     * 发起Get请求
     *
     * @param urlStr
     * @return
     */
    public final static byte[] doGetRequestForFile(String urlStr) {

        InputStream is = null;
        byte[] bytes =null;
        ByteArrayOutputStream os = null;
        byte[] buff = new byte[1024];
        int len = 0;
        try {
            URL url = new URL(UriUtils.encodePath(urlStr, DEFAULT_CHARSET));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
            conn.setRequestProperty("charset", "utf-8");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.connect();
            is = conn.getInputStream();
            os = new ByteArrayOutputStream();
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
            }
            bytes = os.toByteArray();
            return bytes;
        } catch (IOException e) {
//            log.error("发起请求出现异常:", e);
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
//                    log.error("【关闭流异常】");
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
//                    log.error("【关闭流异常】");
                }
            }
        }

    }

}
